package com.itaming.lycheeframework.mybatisplus.support;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itaming.lycheeframework.support.utils.CollectionUtil;
import com.itaming.lycheeframework.support.utils.StringPool;
import com.itaming.lycheeframework.support.utils.StringUtil;
import com.itaming.lycheeframework.support.web.Query;
import lombok.experimental.UtilityClass;

import java.util.List;

/**
 * 查询助手类
 *
 * @author A.Ming
 */
@UtilityClass
public class QueryHelper {

    /**
     * 获取分页对象
     *
     * @param query 分页排序查询参数
     * @return 分页对象
     */
    public static <T> IPage<T> page(Query query) {
        Page<T> page = new Page<>();

        if (query != null) {
            // 当前页
            if (query.getPage() != null && query.getPage() >= 1) {
                page.setCurrent(query.getPage());
            }

            // 每页条数
            if (query.getSize() != null && query.getSize() >= 1) {
                page.setSize(query.getSize());
            }

            // 添加排序字段
            addOrder(page, query.getSort());
        }

        return page;
    }

    /**
     * 获取QueryWrapper
     *
     * @param entity 查询条件实体对象
     * @return QueryWrapper
     */
    public static <T> QueryWrapper<T> wrapper(T entity) {
        return new QueryWrapper<>(entity);
    }

    /**
     * 添加排序字段
     *
     * @param page 分页对象
     * @param sort 排序字段列表
     */
    private static void addOrder(Page<?> page, List<String> sort) {
        if (CollectionUtil.isEmpty(sort)) {
            return;
        }

        for (String s : sort) {
            if (StringUtil.isBlank(s)) {
                continue;
            }

            if (!StringUtil.contains(s, StringPool.COLON)) {
                page.addOrder(OrderItem.asc(s));
                continue;
            }

            String[] split = StringUtil.split(s, StringPool.COLON);

            switch (StringUtil.strip(split[1])) {
                case "":
                case "asc":
                    page.addOrder(OrderItem.asc(split[0]));
                    break;
                case "desc":
                    page.addOrder(OrderItem.desc(split[0]));
                    break;
                default:
                    break;
            }
        }
    }


}
